package JDBC;

import java.io.*;
import java.sql.*;

/**
 * 测试BLOB 二进制大对象的使用
 */
public class demo9 {

    public static void main(String[] args) {
        Connection conn= null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream is = null;
        OutputStream os =null;
        try {
            //加载类驱动
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/zz?characterEncoding=UTF-8","root","123456");

//            ps = conn.prepareStatement("INSERT INTO user (userName,headerImg) VALUES (?,?)");
//            ps.setString(1,"张哲");
//            ps.setBlob(2,new FileInputStream("src/IO/ppp.png"));//以二进制流的形式
//            ps.execute();

            ps = conn.prepareStatement("SELECT * FROM user WHERE id=?");
            ps.setObject(1,"40025");
            rs =  ps.executeQuery();
            while (rs.next()){
                Blob b = rs.getBlob("headerImg");//始终操作的是流
                is = b.getBinaryStream();
                os = new FileOutputStream("src/JDBC/ppp.png");
                int temp = 0;
                while ((temp=is.read())!=-1){
//                    System.out.print((char) temp);//打印的乱码，控制台无法显示图片
                    os.write(temp);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null){
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(is!=null){
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(rs!=null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(ps!=null){
                    ps.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
